<template>
  <a-page bg="/statics/map.jpg" searchDisabled>
    <div slot="nav">
      <div class="row justify-center">
        <q-tabs v-model="type" color="" text-color="black" class="col-xl-3 col-lg-4 col-md-5 col-sm-6" align="justify">
          <q-tab name="phone" label="手机注册"/>
          <q-tab name="email" label="邮箱注册"/>
        </q-tabs>
      </div>
    </div>
    <div class="row justify-center">
      <div class="border-radius-3 col-xl-4 col-lg-4 col-md-5 col-sm-6 q-px-md bg-white q-gutter-y-sm"
           :class="{'q-my-md q-py-md': $q.screen.gt.xs}">
        <q-input
          v-if="type==='phone'"
          label="手机"
          :error-message="phoneError"
          :error="!!phoneError"
          dense
          v-model="phone"
          :class="{'q-mt-sm': $q.screen.gt.md}"
          clearable
          name="reg-username"
          hint="11位数字"
          maxlength="11"></q-input>
        <q-input
          v-else
          label="邮箱"
          :error-message="emailError"
          :error="!!emailError"
          dense
          v-model="email"
          autofocus
          type="email"
          :class="{'q-mt-sm': $q.screen.gt.md}"
          clearable
          maxlength="32"
          hint="8-32位"
          name="reg-username"></q-input>
        <q-input
          :disable="type === 'phone' ? $v.phone.$invalid : $v.email.$invalid"
          label="验证码"
          dense
          v-model="verifyCode"
          clearable
          hint="6位"
          maxlength="6">
          <template v-slot:append>
            <q-btn
              :disabled="timer"
              dense
              class="button-dense"
              color="white"
              text-color="primary"
              :label="timer ? countdown+'秒后可重新发送' : '获取验证码'"
              @click="sendCode"
              style="padding-top: 0!important;padding-bottom: 0!important;"/>
          </template>
        </q-input>
          <q-input
            label="用户名"
            :error-message="userError"
            :error="!!userError"
            dense
            v-model="username"
            maxlength="16"
            hint="8-16位"
            name="reg-username"></q-input>
          <q-input
            label="密码"
            dense
            v-model="password"
            type="password"
            hint="8-16位"
            maxlength="16"
            name="reg-password"></q-input>
        <div class="justify-center row q-mt-sm">
          <q-btn v-if="type === 'phone'" :disable="$v.phoneGroup.$invalid" color="primary" class="q-my-md full-width"
                 @click="register('phone')">注册
          </q-btn>
          <q-btn v-else :disable="$v.emailGroup.$invalid" color="primary" class="q-my-md full-width"
                 @click="register('email')">注册
          </q-btn>
        </div>
        <a-oauth></a-oauth>
        <div class="row q-mt-lg justify-center">
          <a href="/login">
            <q-btn color="primary" flat label="登录"/>
          </a>
        </div>
      </div>
    </div>
  </a-page>
</template>

<script>
  import LoginNav from './nav/login'
  import { required, email, integer, minLength, maxLength } from 'vuelidate/lib/validators'
  import { timerMixin } from '../components/mixin/time'
  import { authMixin } from '../components/mixin/auth'

  export default {
    name: 'PageRegister',
    components: { LoginNav },
    mixins: [timerMixin, authMixin],
    data () {
      return {
        username: '',
        password: '',
        phone: '',
        email: '',
        verifyCode: '',
        type: 'phone',
        auto: true,
        usernameUnique: true,
        emailUnique: true,
        phoneUnique: true
      }
    },
    validations: {
      username: {
        required,
        async isUnique (value) {
          const result = await this.unique(value, 'username')
          return result
        },
        minLength: minLength(2),
        maxLength: maxLength(32)
      },
      password: {
        required, minLength: minLength(8), maxLength: maxLength(16)
      },
      verifyCode: {
        required, minLength: minLength(6), maxLength: maxLength(6)
      },
      phone: {
        required,
        async isUnique (value) {
          const result = await this.unique(value, 'phone')
          return result
        },
        minLength:
          minLength(11),
        maxLength: maxLength(11),
        integer
      },
      email: {
        required,
        isUnique (value) {
          const result = this.unique(value, 'email')
          return result
        },
        minLength: minLength(4),
        maxLength: maxLength(32),
        email
      },
      phoneGroup: ['username', 'password', 'verifyCode', 'phone'],
      emailGroup: ['username', 'password', 'verifyCode', 'email']
    },
    computed: {
      phoneError () {
        const validation = this.$v.phone
        if (!validation.required || this.loading) {
          return
        }
        if (!validation.minLength) {
          return '手机号码格式不正确'
        }

        if (!this.phoneUnique) {
          return '手机号码已经被注册'
        }

        return ''
      },
      userError () {
        const validation = this.$v.username
        if (!validation.required || this.loading) {
          return
        }
        if (!validation.minLength) {
          return '用户名不少于两位'
        }
        if (!this.usernameUnique) {
          return '用户名已经被注册'
        }

        return ''
      },
      emailError () {
        const validation = this.$v.email
        if (!validation.required || this.loading) {
          return
        }

        if (!validation.email) {
          return '邮箱格式不正确'
        }
        if (!this.emailUnique) {
          return '邮箱已经被注册'
        }

        return ''
      }
    },
    methods: {
      async sendCode () {
        if (this.timer) {
          return null
        }
        this.startTimer()

        let reqData = {}

        if (!this.type) {
          return null
        } else if (this.type === 'phone') {
          reqData.phone = this.phone
        } else if (this.type === 'email') {
          reqData.email = this.email
        }

        const { status, data } = await this.postRequest({
          api: '/api/user/register_code/',
          data: reqData
        })

        if (status === 200) {
          const typeCH = this.type === 'phone' ? '手机' : '邮箱'

          this.notify('success', `已向你的注册${typeCH}发送验证码`)
        } else {
          const error = data.detail
          if (error === 'phone已存在') {
            this.notify('error', '发送失败，你的手机号码已经被注册')
          }
          this.notify('error', '发送验证码失败，请稍后重试')
        }
      },
      async register (type) {
        let resData = {
          username: this.username,
          password: this.password,
          code: this.verifyCode
        }

        if (type === 'phone') {
          resData.phone = this.phone
        } else {
          resData.email = this.email
        }

        const { status, data } = await this.postRequest({
          api: '/api/user/register/',
          data: resData
        })

        if (status === 200) {
          this.authorize(data)
          this.$router.push('/account/settings/head/')
        } else {
          this.notify('error', '注册失败：' + data.detail)
        }
      },
      async unique (value, type) {
        this[type + 'Unique'] = true

        if (!value) {
          return true
        }

        if (type === 'email' && this.$v.email.email === false) {
          return true
        }

        if (type === 'phone' && value.length !== 11) {
          return true
        }

        if (type === 'username' && value.length < 2) {
          return true
        }

        const data = {}

        data[type] = value

        const { status } = await this.postRequest({
          api: '/api/user/checkout_register/',
          data
        })

        if (status === 200) {
          return true
        } else {
          setTimeout(() => {
            this[type + 'Unique'] = false
          }, 0)
          return false
        }
      }
    }
  }
</script>

<style lang="stylus">

</style>
